$(function() {
//    $(".div-list").perfectScrollbar({
//        wheelSpeed: 20,
//        wheelPropagation: true
//    });

    cart_del_hover();

})
function cart_del_hover() {
    $(".div-article").hover(function() {
        $(this).find('.article-del').show();
    }, function() {
        $(this).find('.article-del').hide();
    })
}
function addToOrder(obj, id) {
    /*****抛物线******/
    $("#element").text(obj.data("price"));
    var addTop = obj.offset().top;
    var addLeft = obj.offset().left;
    $('#element').css({
        "left": addLeft,
        "top": addTop,
        "display": "block",
        
    })
    var element = document.getElementById("element"), target = document.getElementById("cart-num");
    // 抛物线元素的的位置标记
    var parabola = funParabola(element, target).mark();
    parabola.init();
    /*****抛物线over******/
    if (!obj.hasClass('active')) {
        obj.addClass('active');
    }
    var name = obj.attr("data-name");
    var price = obj.attr("data-price");
    $.post(getUrl("Cart/addToCart"), {
        id: id,
        num: 1
    }, function(data) {
        var shop_id = $("#shop_info").data("id");
        var shop_name = $("#shop_info").data("name");
        var div_shop = "<div class='div-list' data-sid='" + shop_id + "'id='shop_" + shop_id + "'>\n\
    <div class='shop-header'>\n\
        <div class='shop-check'>\n\
            <input class='shop-input check_shop' type='checkbox' autocomplete='off' onclick=check_shop($(this)) value='" + shop_id + "' checked=''>\n\
        </div>\n\
        <div class='shop-title'>\n\
            <span class='label label-danger tt'>" + shop_name + "</span>\n\
            <strong class='shop-price'>805.0</strong>\n\
        </div>\n\
    </div>";
        var div_goods = "    <div class='div-article' data-price='" + price + "' data-id='" + id + "'>\n\
        <div class='article-check'>\n\
            <input class='article-input check_goods' type='checkbox' checked='' value='" + id + "' data-pay='" + price + "' onclick=check_goods($(this)) autocomplete='off' name='id[]'>\n\
        </div>\n\
        <div class='article-detail'>\n\
            <p title='" + name + "'>" + name + "</p>\n\
        </div>\n\
        <div class='article-num' data-total=''>\n\
            <a class='article-minus' onclick=cart_goods_minus($(this)) hidefocus='true'>\n\
                <i class='icon-minus-sign'></i>\n\
            </a>\n\
            <input class='article-quantity' autocomplete='off' value='1' name='num[]' id='num_" + id + "'>\n\
            <a class='article-plus' onclick=cart_goods_plus($(this)) hidefocus='true'>\n\
                <i class='icon-plus-sign'></i>\n\
            </a>\n\
        </div>\n\
        <div class='article-cost'>\n\
            <a class='article-del' data-tmc='del' title='删除' onclick=cart_goods_del($(this)) style='display: none;'>\n\
                <i class='icon-remove-circle'></i>\n\
            </a>\n\
            <strong class='span-price'>" + price + "</strong>\n\
        </div>\n\
        <div class='cl'></div>\n\
    </div>";
        if ($("#shop_" + shop_id).length == 0) {
            div_goods = div_shop + div_goods + "</div>";
            $("#cart_lists").append(div_goods);
        } else {
            if ($("#num_" + id).length == 0) {
                $("#shop_" + shop_id).append(div_goods);
            } else {
                var num = parseInt($("#num_" + id).val());
                $("#num_" + id).val(num + 1);
            }

        }
        getCartChosePrice();
        cart_del_hover();
    }, "json")
}
function toggleCartBox(obj) {

    var num = parseInt($(".cart-num").text());
    if (num == 0) {
        for (var i = 0; i < 4; i++) {
            $(".cart-num").animate({opacity: "0.1"}, 100);
            $(".cart-num").animate({opacity: "1"}, 100);
        }
        obj.addClass('cart-bar-visited')
    }
    if (!obj.hasClass('cart-bar-visited')) {//显示
        $('.close-cart').show();
        $('.cart-bar').addClass('cart-bar-visited');
        $('.shop-bar').addClass('shop-visited');
        $('.shop-cart,.list-bottom').stop().animate({
            right: 0
        }, 400);
    } else {//隐藏
        $('.close-cart').hide();
        $('.cart-bar').removeClass('cart-bar-visited');
        $('.shop-bar').removeClass('shop-visited');
        $('.shop-cart,.list-bottom').animate({
            right: "-280px"
        }, 400);
    }
}
function checkCartCheckboxAll() {//检测所有多选框
    var len = $("#cart_lists").find("input[type=checkbox]").length;
    var len2 = $("#cart_lists").find("input[type=checkbox]:checked").length;
    if (len == len2) {
        $(".check_cart").prop("checked", true);
    } else {
        $(".check_cart").prop("checked", false);
    }
    getCartChosePrice();
}
function check_cart(obj) {
    var checked = obj.prop("checked");
    if (checked == true) {
        $("#cart_area").find("input[type=checkbox]").prop("checked", true);
    } else {
        $("#cart_area").find("input[type=checkbox]").prop("checked", false);
    }
    getCartChosePrice();
}

function check_shop(obj) {
    var checked = obj.prop("checked");
    var area = obj.parents(".div-list");
    if (checked == true) {
        area.find("input[type=checkbox]").prop("checked", true);
    } else {
        area.find("input[type=checkbox]").prop("checked", false);
    }
    checkCartCheckboxAll();
}


function check_goods(obj) {
    var area = obj.parents(".div-list").children(".div-article");
    var len = area.find("input[type=checkbox]").length;
    var len2 = area.find("input[type=checkbox]:checked").length;
    if (len == len2 && len2 > 0) {
        area.prev('.shop-header').find("input[type=checkbox]").prop("checked", true);
    } else {
        area.prev('.shop-header').find("input[type=checkbox]").prop("checked", false);
    }
    checkCartCheckboxAll();
    getCartChosePrice();

}

function cart_goods_plus(obj) {
    var num = parseInt(obj.prev("input").val());
    obj.prev("input").val(num + 1);
    var price = obj.parents(".div-article").data("price");

    $.post(getUrl("Cart/addCut"), {
        id: obj.parents(".div-article").data("id"),
        num: (num + 1)
    }, function(data) {
        getCartChosePrice();
    })
}
function cart_goods_minus(obj) {
    var num = parseInt(obj.next("input").val());
    if (num > 1) {
        obj.next("input").val(num - 1);
        var price = obj.parents(".td-amount").prev(".td-price").text();

        $.post(getUrl("Cart/addCut"), {
            id: obj.parents(".item-content").find(".check_goods").val(),
            num: (num - 1)
        }, function(data) {
            var sum = price * (num - 1);
            obj.parents(".td-amount").next(".td-sum").find("strong").text(sum.toFixed(1));
            getCartChosePrice();
        })
    }
}
function cart_goods_del(obj) {
    var id = obj.parents(".div-article").data("id");
    $.post(getUrl("Cart/addCut"), {
        id: id,
        num: 0
    }, function(data) {
        if (obj.parents(".div-list").find(".div-article").length <= 1) {
            obj.parents(".div-list").fadeOut(function() {
                obj.parents(".div-list").remove();
                getCartChosePrice();
            });
        } else {
            obj.parents('.div-article').fadeOut(function() {
                obj.parents('.div-article').remove();
                getCartChosePrice();
            });
        }
        $("#btn_" + id).removeClass("active");
    })
}
function getCartChosePrice() {
    var total = 0;
    var cart_num = 0;
    var cart_num_total = 0;
    $(".check_goods").each(function() {
        var p = $(this).parents(".div-article");
        var num = parseInt(p.find(".article-quantity").val());
        if ($(this).prop("checked") == true) {

            var price = parseFloat(p.data("price"));
            cart_num += num;
            total += price * num;
        }
        cart_num_total += num;
    })
    $("#total_price_cart").text(total.toFixed(1));
    if (total > 0) {
        $(".btn-pay").removeClass('disabled')
    } else {
        $(".btn-pay").addClass('disabled')
    }
    $(".has-checked").text(cart_num);
    $(".cart-num,#cartnum").text(cart_num_total);
    $(".div-list").each(function() {
        var total_shop = 0;
        $(this).find(".div-article").each(function() {
            var checked = $(this).find(".check_goods").prop("checked");
            if (checked == true) {
                var num = parseInt($(this).find(".article-quantity").val());
                var price = parseFloat($(this).data("price"));
                total_shop += price * num;
            }
        })
        $(this).find(".shop-price").text(total_shop.toFixed(1));
    })
}
function btn_cart_submit() {
    document.form_cart.submit();
}
var funParabola = function(element, target, options) {
    /*
     * 网页模拟现实需要一个比例尺
     * 如果按照1像素就是1米来算，显然不合适，因为页面动不动就几百像素
     * 页面上，我们放两个物体，200~800像素之间，我们可以映射为现实世界的2米到8米，也就是100:1
     * 不过，本方法没有对此有所体现，因此不必在意
     */

    var defaults = {
        speed: 166.67, // 每帧移动的像素大小，每帧（对于大部分显示屏）大约16~17毫秒
        curvature: 0.001, // 实际指焦点到准线的距离，你可以抽象成曲率，这里模拟扔物体的抛物线，因此是开口向下的
        progress: function() {
        },
        complete: function() {
             $('#element').hide();
        }
    };

    var params = {};
    options = options || {};

    for (var key in defaults) {
        params[key] = options[key] || defaults[key];
    }

    var exports = {
        mark: function() {
            return this;
        },
        position: function() {
            return this;
        },
        move: function() {
            return this;
        },
        init: function() {
            return this;
        }
    };

    /* 确定移动的方式 
     * IE6-IE8 是margin位移
     * IE9+使用transform
     */
    var moveStyle = "margin", testDiv = document.createElement("div");
    if ("oninput" in testDiv) {
        ["", "ms", "webkit"].forEach(function(prefix) {
            var transform = prefix + (prefix ? "T" : "t") + "ransform";
            if (transform in testDiv.style) {
                moveStyle = transform;
            }
        });
    }

    // 根据两点坐标以及曲率确定运动曲线函数（也就是确定a, b的值）
    /* 公式： y = a*x*x + b*x + c;
     */
    var a = params.curvature, b = 0, c = 0;

    // 是否执行运动的标志量
    var flagMove = true;

    if (element && target && element.nodeType == 1 && target.nodeType == 1) {
        var rectElement = {}, rectTarget = {};

        // 移动元素的中心点位置，目标元素的中心点位置
        var centerElement = {}, centerTarget = {};

        // 目标元素的坐标位置
        var coordElement = {}, coordTarget = {};

        // 标注当前元素的坐标
        exports.mark = function() {
            if (flagMove == false)
                return this;
            if (typeof coordElement.x == "undefined")
                this.position();
            element.setAttribute("data-center", [coordElement.x, coordElement.y].join());
            target.setAttribute("data-center", [coordTarget.x, coordTarget.y].join());
            return this;
        }

        exports.position = function() {
            if (flagMove == false)
                return this;

            var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft,
                    scrollTop = document.documentElement.scrollTop || document.body.scrollTop;

            // 初始位置
            if (moveStyle == "margin") {
                element.style.marginLeft = element.style.marginTop = "0px";
            } else {
                element.style[moveStyle] = "translate(0, 0)";
            }

            // 四边缘的坐标
            rectElement = element.getBoundingClientRect();
            rectTarget = target.getBoundingClientRect();

            // 移动元素的中心点坐标
            centerElement = {
                x: rectElement.left + (rectElement.right - rectElement.left) / 2 + scrollLeft,
                y: rectElement.top + (rectElement.bottom - rectElement.top) / 2 + scrollTop
            };

            // 目标元素的中心点位置
            centerTarget = {
                x: rectTarget.left + (rectTarget.right - rectTarget.left) / 2 + scrollLeft,
                y: rectTarget.top + (rectTarget.bottom - rectTarget.top) / 2 + scrollTop
            };

            // 转换成相对坐标位置
            coordElement = {
                x: 0,
                y: 0
            };
            coordTarget = {
                x: -1 * (centerElement.x - centerTarget.x),
                y: -1 * (centerElement.y - centerTarget.y)
            };

            /*
             * 因为经过(0, 0), 因此c = 0
             * 于是：
             * y = a * x*x + b*x;
             * y1 = a * x1*x1 + b*x1;
             * y2 = a * x2*x2 + b*x2;
             * 利用第二个坐标：
             * b = (y2+ a*x2*x2) / x2
             */
            // 于是
            b = (coordTarget.y - a * coordTarget.x * coordTarget.x) / coordTarget.x;

            return this;
        };

        // 按照这个曲线运动
        exports.move = function() {
            // 如果曲线运动还没有结束，不再执行新的运动
            if (flagMove == false)
                return this;

            var startx = 0, rate = coordTarget.x > 0 ? 1 : -1;

            var step = function() {
                // 切线 y'=2ax+b
                var tangent = 2 * a * startx + b; // = y / x
                // y*y + x*x = speed
                // (tangent * x)^2 + x*x = speed
                // x = Math.sqr(speed / (tangent * tangent + 1));
                startx = startx + rate * Math.sqrt(params.speed / (tangent * tangent + 1));

                // 防止过界
                if ((rate == 1 && startx > coordTarget.x) || (rate == -1 && startx < coordTarget.x)) {
                    startx = coordTarget.x;
                }
                var x = startx, y = a * x * x + b * x;

                // 标记当前位置，这里有测试使用的嫌疑，实际使用可以将这一行注释
                element.setAttribute("data-center", [Math.round(x), Math.round(y)].join());

                // x, y目前是坐标，需要转换成定位的像素值
                if (moveStyle == "margin") {
                    element.style.marginLeft = x + "px";
                    element.style.marginTop = y + "px";
                } else {
                    element.style[moveStyle] = "translate(" + [x + "px", y + "px"].join() + ")";
                }

                if (startx !== coordTarget.x) {
                    params.progress(x, y);
                    window.requestAnimationFrame(step);
                } else {
                    // 运动结束，回调执行
                    params.complete();
                    flagMove = true;
                 
                }
            };
            window.requestAnimationFrame(step);
            flagMove = false;

            return this;
        };

        // 初始化方法
        exports.init = function() {
            this.position().mark().move();
        };
    }

    return exports;
};